/**
 * Actor 桥接层 - 提供与 WASM Actor 交互的 API
 */

import { WasmBridge, WasmBridgeFactory } from './wasmBridge';
import { WasmEventListener, WasmEventManager, WasmEventManagerFactory, WasmEventType } from './wasmEvents';

/**
 * Actor 消息接口
 */
export interface ActorMessage {
  type: string;
  [key: string]: any;
}

/**
 * Actor 标识符接口
 */
export interface ActorPID {
  id: string;
  address: string;
  name?: string;
}

/**
 * Actor 事件类型
 */
export enum ActorEventType {
  CREATED = 'actor_created',
  STOPPED = 'actor_stopped',
  MESSAGE_SENT = 'message_sent',
  MESSAGE_RECEIVED = 'message_received',
  ERROR = 'actor_error'
}

/**
 * Actor 事件监听器类型
 */
export type ActorEventListener = (data: any) => void;

/**
 * Actor 桥接类 - 封装 WASM Actor 操作
 */
export class ActorBridge {
  private wasmBridge: WasmBridge;
  private eventManager: WasmEventManager;
  private initialized: boolean = false;
  private actorEventListeners: Map<ActorEventType, Set<ActorEventListener>> = new Map();

  /**
   * 构造函数
   * @param wasmBridge WASM 桥接实例，如不提供将使用默认实例
   * @param eventManager 事件管理器实例，如不提供将使用默认实例
   */
  constructor(wasmBridge?: WasmBridge, eventManager?: WasmEventManager) {
    this.wasmBridge = wasmBridge || WasmBridgeFactory.getInstance();
    this.eventManager = eventManager || WasmEventManagerFactory.getInstance();
    
    // 初始化事件监听器映射
    Object.values(ActorEventType).forEach(type => {
      this.actorEventListeners.set(type as ActorEventType, new Set());
    });
    
    // 设置 WASM 事件监听
    this.setupWasmEventListeners();
  }

  /**
   * 设置 WASM 事件监听
   */
  private setupWasmEventListeners(): void {
    // 监听 Actor 创建事件
    this.eventManager.addEventListener(WasmEventType.ACTOR_CREATED, (data) => {
      this.dispatchActorEvent(ActorEventType.CREATED, data);
    });
    
    // 监听 Actor 停止事件
    this.eventManager.addEventListener(WasmEventType.ACTOR_STOPPED, (data) => {
      this.dispatchActorEvent(ActorEventType.STOPPED, data);
    });
    
    // 监听消息接收事件
    this.eventManager.addEventListener(WasmEventType.MESSAGE_RECEIVED, (data) => {
      this.dispatchActorEvent(ActorEventType.MESSAGE_RECEIVED, data);
    });
    
    // 监听错误事件
    this.eventManager.addEventListener(WasmEventType.ERROR, (data) => {
      this.dispatchActorEvent(ActorEventType.ERROR, data);
    });
  }

  /**
   * 初始化 Actor 桥接
   * @param wasmPath WASM 文件路径
   */
  async initialize(wasmPath?: string): Promise<void> {
    if (!this.initialized) {
      await this.wasmBridge.initialize(wasmPath);
      
      // 注册默认消息处理器
      this.registerMessageHandler('handleGreeting', (message: ActorMessage) => {
        console.log(`[ActorBridge] 收到问候消息: ${JSON.stringify(message)}`);
        this.dispatchActorEvent(ActorEventType.MESSAGE_RECEIVED, { message });
        return { response: `默认响应: 收到 ${message.type}` };
      });
      
      this.initialized = true;
    }
  }

  /**
   * 注册消息处理器
   * @param handlerName 处理器名称
   * @param handler 处理器函数
   */
  registerMessageHandler(handlerName: string, handler: (message: ActorMessage) => any): void {
    const wrappedHandler = (message: ActorMessage) => {
      // 触发消息接收事件
      this.dispatchActorEvent(ActorEventType.MESSAGE_RECEIVED, { handlerName, message });
      return handler(message);
    };
    
    this.wasmBridge.registerTSFunction(handlerName, wrappedHandler);
  }

  /**
   * 创建 Actor
   * @param actorName Actor 名称
   * @returns Actor PID
   */
  async createActor(actorName: string): Promise<ActorPID> {
    this.ensureInitialized();
    try {
      const pid = await this.wasmBridge.invokeGoFunction('createActor', actorName);
      this.dispatchActorEvent(ActorEventType.CREATED, { actorName, pid });
      return pid;
    } catch (error) {
      this.dispatchActorEvent(ActorEventType.ERROR, { operation: 'createActor', actorName, error });
      throw error;
    }
  }

  /**
   * 发送消息到 Actor
   * @param pid Actor PID
   * @param message 消息对象
   * @returns 响应结果
   */
  async sendMessage(pid: ActorPID, message: ActorMessage): Promise<any> {
    this.ensureInitialized();
    try {
      this.dispatchActorEvent(ActorEventType.MESSAGE_SENT, { pid, message });
      return await this.wasmBridge.invokeGoFunction('sendMessage', pid, message);
    } catch (error) {
      this.dispatchActorEvent(ActorEventType.ERROR, { operation: 'sendMessage', pid, message, error });
      throw error;
    }
  }

  /**
   * 停止 Actor
   * @param pid Actor PID
   * @returns 成功状态
   */
  async stopActor(pid: ActorPID): Promise<{ success: boolean }> {
    this.ensureInitialized();
    try {
      const result = await this.wasmBridge.invokeGoFunction('stopActor', pid);
      this.dispatchActorEvent(ActorEventType.STOPPED, { pid, result });
      return result;
    } catch (error) {
      this.dispatchActorEvent(ActorEventType.ERROR, { operation: 'stopActor', pid, error });
      throw error;
    }
  }

  /**
   * 获取 WASM 模块版本
   * @returns 版本字符串
   */
  async getVersion(): Promise<string> {
    this.ensureInitialized();
    try {
      return await this.wasmBridge.invokeGoFunction('getVersion');
    } catch (error) {
      this.dispatchActorEvent(ActorEventType.ERROR, { operation: 'getVersion', error });
      throw error;
    }
  }

  /**
   * 添加 Actor 事件监听器
   * @param eventType 事件类型
   * @param listener 监听器函数
   */
  addEventListener(eventType: ActorEventType, listener: ActorEventListener): void {
    const listeners = this.actorEventListeners.get(eventType);
    if (listeners) {
      listeners.add(listener);
    }
  }

  /**
   * 移除 Actor 事件监听器
   * @param eventType 事件类型
   * @param listener 监听器函数
   */
  removeEventListener(eventType: ActorEventType, listener: ActorEventListener): void {
    const listeners = this.actorEventListeners.get(eventType);
    if (listeners) {
      listeners.delete(listener);
    }
  }

  /**
   * 触发 Actor 事件
   * @param eventType 事件类型
   * @param data 事件数据
   */
  private dispatchActorEvent(eventType: ActorEventType, data: any): void {
    const listeners = this.actorEventListeners.get(eventType);
    if (listeners) {
      listeners.forEach(listener => {
        try {
          listener(data);
        } catch (error) {
          console.error(`Actor 事件监听器错误 (${eventType}):`, error);
        }
      });
    }
  }

  /**
   * 确保桥接已初始化
   */
  private ensureInitialized(): void {
    if (!this.initialized) {
      throw new Error('Actor 桥接尚未初始化，请先调用 initialize()');
    }
  }
}

/**
 * 创建 ActorBridge 实例
 * @returns ActorBridge 实例
 */
export function createActorBridge(): ActorBridge {
  return new ActorBridge();
} 